﻿using Api.Shared.Model;
using Api.Shared.Model.Impl;
using Api.Shared.Model.Yanji;
using Api.Shared.MyPlc.S7;
using Api.Shared.Utils;
using Api.Shared.Utils.Yanji;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using S7.Net;

namespace FitterTest.Controllers
{
    [Route("api/private/v1/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class PlcController : ControllerBase
    {
        private IS7ConnService s7ConnService;
        private readonly ILogger<PlcController> logger;
        private readonly IConfiguration configuration;
        private readonly DbData dbData;
        private readonly IMemoryCache cache;
        private readonly ApiData apiData;

        public PlcController(
            IS7ConnService s7ConnService,
            ILogger<PlcController> logger,
            IConfiguration configuration,
            DbData dbData,
            IMemoryCache cache,
            ApiData apiData
        )
        {
            this.s7ConnService = s7ConnService;
            this.logger = logger;
            this.configuration = configuration;
            this.dbData = dbData;
            this.cache = cache;
            this.apiData = apiData;
            ip = configuration.GetSection("PlcIp").Value ?? string.Empty;
        }

        private string ip = string.Empty;

        [HttpGet]
        public async Task<IActionResult> ReadTest()
        {
            using Plc plc = new Plc(CpuType.S71500, ip, 0, 1);
            plc.Open();
            plc.ReadTimeout = 620;
            plc.WriteTimeout = 620;

            var a = await plc.ReadClassAsync<DB91WorkOrder>(91, 0);

            //logger.LogWarning(str1);
            return Ok(a);
        }

        [HttpGet]
        public ActionResult<MyApiResponse<ApiData>> Test3()
        {
            //logger.LogWarning(plcData.Short1.ToString());
            //内存缓存
            if (cache.TryGetValue("myCacheKey", out ApiData? wpfData))
            {
                if (wpfData == null)
                {
                    return new MyApiResponse<ApiData>(true, new ApiData());
                }
                var res = new MyApiResponse<ApiData>(true, wpfData);
                return res;
            }
            else
            {
                var data = apiData;
                var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(
                    TimeSpan.FromSeconds(0.5)
                ); // 设置缓存过期时间
                cache.Set("myCacheKey", data, cacheEntryOptions);

                var res = new MyApiResponse<ApiData>(true, data);
                //return new MyApiResponse<ApiData>(true, new ApiData() { Bool1 = true, Float1 = 5.1f});
                return res;
            }

            //double A = plcData.Float1;
            //double B = plcData.Float2;
            //double C = plcData.Float3;
            //var a = new
            //{
            //    A = A,
            //    B = B,
            //    C = C
            //};
            //return Ok();
        }

        [HttpGet]
        public ActionResult<RobStationData> RobStation()
        {
            if (cache.TryGetValue("kxData", out RobStationData? robData))
            {
                if (robData == null)
                {
                    return new RobStationData();
                }
                return robData;
            }
            else
            {
                //apiData
                RobStationData data =
                    new()
                    {
                        Kr500CurrentValue = apiData.Float2.ToString("0.00"),
                        Kr500Pgno = apiData.Short11.ToString(),
                        Kr500ProId = apiData.Short13.ToString(),

                        Kr16CurrentValue = apiData.Float4.ToString("0.00"),
                        Kr16Pgno = apiData.Short12.ToString(),

                        Kr500State = apiData.Short1.ToString(),
                        Kr16State = apiData.Short2.ToString(),

                        DZ1Servo = apiData.Short3.ToString(),
                        DZ2Servo = apiData.Short4.ToString(),
                        DZ3Servo = apiData.Short5.ToString(),
                        KJ1Servo = apiData.Short6.ToString(),
                        KJ2Servo = apiData.Short7.ToString(),
                        KJ3Servo = apiData.Short8.ToString(),
                        AxisServo = apiData.Short9.ToString(),
                        PolishServo = apiData.Short10.ToString(),
                        CameraX = apiData.Float5.ToString("0.00"),
                        CameraY = apiData.Float6.ToString("0.00"),
                        DZ1ActPos = apiData.Float7.ToString("0.00"),
                        DZ1SetPos = apiData.Float8.ToString("0.00"),
                        DZ1ActVel = apiData.Float9.ToString("0.00"),
                        DZ2ActPos = apiData.Float10.ToString("0.00"),
                        DZ2SetPos = apiData.Float11.ToString("0.00"),
                        DZ2ActVel = apiData.Float12.ToString("0.00"),
                        DZ3ActPos = apiData.Float13.ToString("0.00"),
                        DZ3SetPos = apiData.Float14.ToString("0.00"),
                        DZ3ActVel = apiData.Float15.ToString("0.00"),

                        KJ1ActPos = apiData.Float16.ToString("0.00"),
                        KJ1SetPos = apiData.Float17.ToString("0.00"),
                        KJ1ActVel = apiData.Float18.ToString("0.00"),

                        KJ2ActPos = apiData.Float19.ToString("0.00"),
                        KJ2SetPos = apiData.Float20.ToString("0.00"),
                        KJ2ActVel = apiData.Float21.ToString("0.00"),

                        KJ3ActPos = apiData.Float22.ToString("0.00"),
                        KJ3SetPos = apiData.Float23.ToString("0.00"),
                        KJ3ActVel = apiData.Float24.ToString("0.00"),

                        AxisActPos = apiData.Float25.ToString("0.00"),
                        AxisSetPos = apiData.Float26.ToString("0.00"),
                        AxisActVel = apiData.Float27.ToString("0.00"),

                        PolishActPos = apiData.Float28.ToString("0.00"),
                        PolishSetPos = apiData.Float29.ToString("0.00"),
                        PolishActVel = apiData.Float30.ToString("0.00"),

                        ProductName = apiData.Str1,
                        ProductType = apiData.Short14.ToString(),
                        ProductLength = apiData.Float31.ToString("0.00"),
                        ProductWidth = apiData.Float32.ToString("0.00"),
                        ArcCurrent = apiData.Float105.ToString(),
                        ArcVol = apiData.Float106.ToString(),
                        ArcVel = apiData.Float107.ToString(),
                        BigDizuoNum = apiData.Short107.ToString(),
                        SmallDizuoNum = apiData.Short108.ToString(),
                        KjNum = apiData.Short106.ToString(),
                        Yuanzhu1Num = apiData.Short104.ToString(),
                        Yuanzhu2Num = apiData.Short105.ToString(),
                        HansiConsum = apiData.Float1023.ToString(),
                        GasConsum = apiData.Float1024.ToString(),
                        Kr16v1 = apiData.Float108.ToString(),
                        Kr16v2 = apiData.Float109.ToString(),
                        Kr16v3 = apiData.Float1010.ToString(),
                        Kr16v4 = apiData.Float1011.ToString(),
                        Kr16v5 = apiData.Float1012.ToString(),
                        Kr16v6 = apiData.Float1013.ToString(),
                        Kr16v7 = apiData.Float1014.ToString(),

                        Kr500v1 = apiData.Float1015.ToString(),
                        Kr500v2 = apiData.Float1016.ToString(),
                        Kr500v3 = apiData.Float1017.ToString(),
                        Kr500v4 = apiData.Float1018.ToString(),
                        Kr500v5 = apiData.Float1019.ToString(),
                        Kr500v6 = apiData.Float1020.ToString(),
                        Kr500v7 = apiData.Float1021.ToString(),
                    };

                var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(
                    TimeSpan.FromSeconds(2)
                ); // 设置缓存过期时间
                cache.Set("kxData", data, cacheEntryOptions);

                return data;
                //var data = apiData;
                //var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(
                //    TimeSpan.FromSeconds(0.5)
                //); // 设置缓存过期时间
                //cache.Set("myCacheKey", data, cacheEntryOptions);

                //var res = new MyApiResponse<ApiData>(true, data);
                //return res;
            }
        }


        [HttpPost]
        public ActionResult<ApiResponse<Person2>> MyClientTest([FromBody] Person2 person)
        {
            ApiResponse<Person2>? resp =
                new()
                {
                    Message = "Success!",
                    Result = person,
                    Status = true,
                    Code = 200
                };
            return resp;
        }
    }
}
